package com.tio.server.web.service;

import com.zengtengpeng.operation.*;
import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * redis 读写操作
 */
@Log4j2
@Service
public class RedissonServer {

    @Autowired
    private RedissonObject redissonObject;

    @Autowired
    private RedissonBinary redissonBinary;

    @Autowired
    private RedissonCollection redissonCollection;

    @PostConstruct
    public void init() {
        log.info("redissonObject:{}", redissonObject);
        log.info("redissonBinary:{}", redissonBinary);
        log.info("redissonCollection:{}", redissonCollection);
        test();
    }

    public void test() {

        redissonObject.setValue("time", System.currentTimeMillis());
        long time = redissonObject.getValue("time");
        log.info("time:{}", time);

        Map<String, String> map = new HashMap<>();
        map.put("test1", "test11");
        map.put("test2", "test22");
        map.put("test3", "test33");
        map.put("test4", "test44");
        //设置值
        redissonCollection.setMapValues("test", map);

        //获取值
        RMap<String, String> test = redissonCollection.getMap("test");

        //如果缓存有值从缓存里面读, 否则从接口函数读实时数据存入redis
        Object test1 = redissonCollection.getMapValue("test", "444", () -> {
            return "获取值";
        }, 2000000L);

        //获取Map ,如果redis没有,则从接口函数中获取存入map 并返回
        RMap<String, String> aaa = redissonCollection.getMap("aaa", () -> {
            Map<String, String> map1 = new HashMap<>();
            map1.put("123", "456");
            map1.put("789", "111");
            return map;
        });

        log.info("test:{}", test);
        log.info("test1:{}", test1);
        log.info("aaa:{}", aaa);

    }

}
